<?php
/**
 * Created by PhpStorm.
 * User: ibenchu-014
 * Date: 2017/1/19
 * Time: 17:20
 */

namespace App\Http\Controllers\Admin;


use App\Category;
use App\Http\Requests\CategroyRequest;
use houdunwang\arr\Arr;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Request;

class CategoryController extends AdminController
{


    public function index()
    {

        /*数组分页*/
        $array = Cache::get('Categroys');
        /*当前页*/
        $nowPage = Request::get('page',1);
        /*每页个数*/
        $perPage = 15;
        /*数据总数*/
        $totalCount = count($array);
        /*切割*/
        $lists = array_slice($array, ($nowPage - 1) * $perPage, $perPage);
        /*返回的数据*/
        $list = new LengthAwarePaginator($lists,$totalCount,$perPage);
        /*自定义地址*/
        $list->setPath('categroys');

        return view('admin.category.index',compact('list'));
    }


    public function create()
    {
        $parent = Cache::get('Categroys');
        return view('admin.category.add',compact('parent'));
    }
    
    public function store(CategroyRequest $request)
    {
        Category::create($request->except('_token'));
        $this->clear();
        return redirect('admin/categroys');
    }
    
    public function edit($id)
    {
        $parent = Cache::get('Categroys');
        $cate = Category::find($id)->toArray();
        return view('admin.category.edit',compact('parent','cate'));
    }


    public function update(CategroyRequest $request,$id)
    {
        Category::where('id',$id)->update($request->except('_token','_method'));
        $this->clear();
        return redirect('admin/categroys');
    }


    public function destroy($id)
    {
        Category::where('id',$id)->delete();
        $this->clear();
        return redirect('admin/categroys');
    }

    /**
     * 更新缓存
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function clear()
    {
        $result = Arr::tree(Category::get()->toArray(),'name','id','pid');
        Cache::forever('Categroys',$result);
        return redirect('admin/categroys');
    }
    
}